package io.tim.mvc_f2.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 反射工具类
 *
 * @author zhangnan
 * @date 2017年3月10日
 *
 */
public final class ReflectionUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);
	
	/**
	 * 创建类实例
	 */
	public static Object newInstance(Class<?> cls) {
		Object instance;
		try {
			instance = cls.newInstance();
		} catch (Exception e) {
			LOGGER.error("new instance failure ==== ", e);
			throw new RuntimeException(e);
		}
		return instance;
	}
	
	/**
	 * 调用类实例的某个方法
	 */
	public static Object invokeMethod(Object obj, Method method, Object... args) {
		Object result;
		try {
			if (!method.isAccessible()) {
				method.setAccessible(true);
				result = method.invoke(obj, args);
				method.setAccessible(false);
			} else {
				result = method.invoke(obj, args);
			}
		} catch (Exception e) {
			LOGGER.error("new instance failure ==== ", e);
			throw new RuntimeException(e);
		}
		return result;
	}
	
	/**
	 * 设置类实例的某个成员变量的值
	 */
	public static void setField(Object obj, Field field, Object value) {
		try {
			if (!field.isAccessible()) {
				field.setAccessible(true);
				field.set(obj, value);
				field.setAccessible(false);
			} else {
				field.set(obj, value);
			}
		} catch (Exception e) {
			LOGGER.error("new instance failure ==== ", e);
			throw new RuntimeException(e);
		}
	}
}
